import 'dart:io';
import 'package:flutter/material.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';

part 'main.g.dart';

@Collection()
class Contact {
  Id id = Isar.autoIncrement;
  late String name;
  late String phoneNumber;
  DateTime createdAt = DateTime.now();

  @override
  String toString() => 'Contact{id: $id, name: $name}';
}

Future<Isar> initializeIsar() async {
  final dir = await getApplicationDocumentsDirectory();
  return Isar.open(
    [ContactSchema],
    directory: dir.path,
    inspector: true,
  );
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final isar = await initializeIsar();

  runApp(MyApp(isar: isar));
}

class MyApp extends StatelessWidget {
  final Isar isar;
  const MyApp({super.key, required this.isar});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: ContactPage(isar: isar),
    );
  }
}

class ContactPage extends StatefulWidget {
  final Isar isar;
  const ContactPage({super.key, required this.isar});

  @override
  State<ContactPage> createState() => _ContactPageState();
}

class _ContactPageState extends State<ContactPage> {
  final _formKey = GlobalKey<FormState>();
  final _nameController = TextEditingController();
  final _phoneController = TextEditingController();

  Future<void> _addContact() async {
    if (!_formKey.currentState!.validate()) return;
    final contact = Contact()
      ..name = _nameController.text
      ..phoneNumber = _phoneController.text;

    print("开始添加联系人: ${_nameController.text}");
    await widget.isar.writeTxn(() async {
      final id = await widget.isar.contacts.put(contact);
      print("写入成功,ID: $id"); // 输出生成的ID
    });

    final savedContact = await widget.isar.contacts.get(contact.id);
    if (savedContact != null) {
      print("验证成功: ${savedContact.name}");
    }

    _nameController.clear();
    _phoneController.clear();
    setState(() {});
  }

  Future<void> _clearAll() async {
    print("删除所有日志");
    await widget.isar.writeTxn(() async {
      await widget.isar.contacts.clear();
    });
    setState(() {});
  }

  Future<void> _addTestData() async {
    print("删除所有日志");
    final contact1 = Contact()
      ..name = "111"
      ..phoneNumber = "111";
    final contact2 = Contact()
      ..name = "222"
      ..phoneNumber = "222";
    final contact3 = Contact()
      ..name = "333"
      ..phoneNumber = "333";
    final users = [contact1, contact2, contact3];
    await widget.isar.writeTxn(() async {
      await widget.isar.contacts.putAll(users); // 批量操作
    });
    setState(() {});
  }

  Future<void> _findOne() async {
    final contacts = await widget.isar.contacts.where().findFirst();
    print("查询到第一个是contacts: $contacts.name");
  }

  Future<void> _findAll() async {
    final contacts = await widget.isar.contacts.where().findAll();
    print("查询到所有联系人: $contacts");
  }

  Future<void> _deleteContact(int id) async {
    await widget.isar.writeTxn(() async {
      await widget.isar.contacts.delete(id);
    });
    setState(() {});
  }

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Contact List'),
        ),
        body: Column(children: [
          Padding(
              padding: const EdgeInsets.all(16.0),
              child: Form(
                key: _formKey,
                child: Column(
                  children: [
                    TextFormField(
                      controller: _nameController,
                      decoration: const InputDecoration(labelText: 'Name'),
                      validator: (value) => value!.isEmpty ? 'Require' : null,
                    ),
                    TextFormField(
                      controller: _phoneController,
                      decoration:
                          const InputDecoration(labelText: 'Phone Number'),
                      validator: (value) => value!.isEmpty ? 'Require' : null,
                    ),
                    const SizedBox(height: 20),
                    ElevatedButton(
                      onPressed: _addContact,
                      child: Text('Add Contact'),
                    ),
                    ElevatedButton(
                      onPressed: _clearAll,
                      child: Text('Clear All'),
                    ),
                    ElevatedButton(
                      onPressed: _addTestData,
                      child: Text('Add 3 Test Contacts'),
                    ),
                    ElevatedButton(
                      onPressed: _findOne,
                      child: Text('Find 111'),
                    ),
                    ElevatedButton(
                      onPressed: _findAll,
                      child: Text('Find all'),
                    ),
                  ],
                ),
              )),
          Expanded(
            child: FutureBuilder<List<Contact>>(
              future: widget.isar.contacts.where().findAll(),
              builder: (context, snapshot) {
                if (!snapshot.hasData) {
                  return Center(child: CircularProgressIndicator());
                }
                final contacts = snapshot.data!;
                return ListView.builder(
                  itemCount: contacts.length,
                  itemBuilder: (context, index) {
                    final contact = contacts[index];
                    return ListTile(
                      title: Text(contact.name),
                      subtitle: Text(contact.phoneNumber),
                      trailing: IconButton(
                        icon: const Icon(Icons.delete, color: Colors.red),
                        onPressed: () => _deleteContact(contact.id),
                      ),
                    );
                  },
                );
              },
            ),
          ),
        ]));
  }
}
